/**
 * 
 */
package com.audi.box.server.handler;

import com.audi.box.controller.DeviceController;
import com.audi.box.controller.HistoryController;
import com.audi.box.controller.MemberController;
import com.audi.box.controller.PlaceController;
import com.audi.box.controller.SceneController;
import com.audi.box.controller.SmartTriggerController;
import com.audi.box.server.message.ActionMessage;
import com.audi.box.server.message.HandlerException;
import com.audi.utils.DBHelper;

import android.content.Context;
import android.util.Log;
import android.util.SparseArray;

/**
 * @author HuyPVA
 * 
 */
public class HandlerFactory {
	private static HandlerFactory handlerFactory;
	private SparseArray<Handler> handlerList;

	/**
	 * 
	 */
	public static HandlerFactory getInstance() {
		return handlerFactory;
	}

	/**
	 * Create handler factory
	 * 
	 * @param context
	 * @return
	 */
	public static HandlerFactory create(Context context) {
		if (context != null) {
			if (handlerFactory == null) {
				handlerFactory = new HandlerFactory(context);
			}

			try {
				DBHelper de = new DBHelper();
				de.addDataTest(context);
			} catch (Exception e) {
				Log.e("app server", e.toString());
			}
			return handlerFactory;
		} else {
			return null;
		}
	}

	private HandlerFactory(Context context) {
		handlerList = new SparseArray<Handler>();
		try {
			handlerList.put(ActionMessage.DEVICE,
					DeviceHandler.getInstance(new DeviceController(context)));

			handlerList.put(ActionMessage.PLACE,
					PlaceHandler.getInstance(new PlaceController(context)));

			handlerList.put(ActionMessage.MEMBER,
					MemberHandler.getInstance(new MemberController(context)));

			handlerList.put(ActionMessage.SMART_TRIGGER, SmartTriggerHandler
					.getInstance(new SmartTriggerController(context)));

			handlerList.put(ActionMessage.SCENE,
					SceneHandler.getInstance(new SceneController(context)));			

			handlerList.put(ActionMessage.HISTORY,
					HistoryHandler.getInstance(new HistoryController(context)));
		} catch (Exception e) {
			Log.e("AudiBox", "[HandlerFactory.java] Initialize handler fail", e);
		}
	}

	/**
	 * Get handler by actionId
	 * 
	 * @param actionId
	 * @return
	 * @throws HandlerException 
	 */
	public Handler getHandler(int actionId) throws HandlerException {
		Handler handler = getInstance().handlerList.get(actionId / 1000);
		if (handler == null)
		{
			throw new HandlerException("Function " + actionId +" not found!!!");
		} 
		return handler;
	}
}
